import io from 'socket.io-client'
import { get } from '@/utils/index.ts'
import store from '@/store/index.ts'
// import { provide } from "vue";

const log = console.log

// let socket: any;
// if (socket != null) {
//   socket.close();
// }

class Socket {
  socket: any = null
  init(url: string, token: string) {
    this.socket && this.socket.close()

    this.socket = io.connect(url, {
      query: {
        room: 'test',
        userId: token,
      },
      transports: ['websocket'],
    })

    // 事件监听
    this.socket.on('connect', () => {
      const id = this.socket.id
      console.log('id is', id)

      log('#connect,', store.state.userName, this.socket)
      // 监听自身 id 以实现 p2p 通讯
      this.socket.on(store.state.userName, msg => {
        log('#receive,', msg)
        store.commit('setMsg', msg)
      })
    })

    // 系统事件
    this.socket.on('disconnect', msg => {
      log('#disconnect', msg)
    })
    this.socket.on('disconnecting', () => {
      log('#disconnecting')
    })

    this.socket.on('error', () => {
      log('#error')
    })
  }

  close() {
    this.socket.close()
  }
}

let useSocket = new Socket()

export default useSocket

// socket = io.connect("http://127.0.0.1:7001/", {
//   query: {
//     room: "test",
//     userId: get("token"),
//   },
//   transports: ["websocket"],
// });

// socket.on("connect", () => {
//   const id = socket.id;

//   log("#connect,", id, socket);

//   // 监听自身 id 以实现 p2p 通讯
//   socket.on(id, (msg) => {
//     log("#receive,", msg);
//   });
// });

// // 接收在线用户信息
// socket.on("online", ({ users }) => {
//   log("#online,", users);
//   // store.commit("setOnline", users);
// });

// // 系统事件
// socket.on("disconnect", (msg) => {
//   log("#disconnect", msg);
// });

// socket.on("disconnecting", () => {
//   log("#disconnecting");
// });

// socket.on("error", () => {
//   log("#error");
// });
